const net = require('net')
const MyTransform = require('./myTransform.js')

const server = net.createServer()

let overageBuffer = null
let ts = new MyTransform()

server.listen('1234','localhost')

server.on('listening',()=>{
  console.log('服务端开始运行 localhost:1234')
})

server.on('connection',(socket)=>{
  socket.on('data', (chunk)=>{
    if(overageBuffer){
      // 非首次读取 连接chunk
      chunk = Buffer.concat([overageBuffer,chunk])
    }
    let packageLen = 0
    while(packageLen = ts.getPackageLen(chunk)){
      // 截取数据
      const packageCon = chunk.slice(0, packageLen)
      // 更新数据
      chunk = chunk.slice(packageLen)
      // 解码/拆包
      const ret = ts.decode(packageCon)
      console.log('拆包后数据',ret)
      // 回写 封包/编码的数据
      socket.write(ts.encode(ret.body, ret.serialNum))
    }
    // 保存剩下没拿完的数据
    overageBuffer = chunk
  })
})
